import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import store from '@/store'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  setRoles({ commit }, view) {
    commit('SET_ROLES', view)
  },
  // user login
  login({ commit }, userInfo) {
    const { userName, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: userName.trim(), password: password }).then(async response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        commit('SET_NAME', userName)
        setToken(data.token)
        for (let key in data) {
          if (key == 'functionPermissionList') {
          } else {
            sessionStorage.setItem(key, data[key])
          }
        }
        let list = data.functionPermissionList || []
        let funcList = list.map(e => e.funcValue)
        sessionStorage.setItem('functionPermissionList', JSON.stringify(funcList))
        const accessRoutes = await store.dispatch('permission/generateRoutes', funcList)
        commit('SET_ROLES', userName == 'admin' ? 'admin' : funcList)
        router.addRoutes(accessRoutes)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        sessionStorage.clear();
        localStorage.clear();
        removeToken()
        resetRouter()
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
